//
//  LLCountDownButton.m
//  walletSDK12580
//
//  Created by Xu Yefeng on 13-6-20.
//  Copyright (c) 2013年 LianLian. All rights reserved.
//

#import "LLCountDownButton.h"
#import "UIView+Sizes.h"

static LLCountDownButton* shareCountdownButton;

@implementation LLCountDownButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        self.countdownInterval = 60;
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)start
{
    if (self.timer != nil) 
    {
        return;
    }
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateButton:) userInfo:nil repeats:YES];

    self.enabled = NO;
    
    self.startTime = [NSDate date];
}

- (void)stop
{
    if (self.timer != nil) {
        [self.timer invalidate];
        self.timer = nil;
        self.startTime = nil;
    }
    
    self.enabled = YES;
    
    [self timerStoped];
}

- (void)updateButton:(NSTimer*)selfTimer
{
    timeInterval = [[NSDate date] timeIntervalSinceDate:self.startTime];
    
    if (timeInterval < self.countdownInterval)
    {
        [self timeLeft:(int)(self.countdownInterval-timeInterval)];
    }
    else
    {
        [self stop];
    }
}

// 重写此函数，实现界面数字更替
- (void)timeLeft:(int)leftTimeInterval
{
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(timeLeft:)]) {
        
        [self.delegate timeLeft:leftTimeInterval];
    }
}

// 重写此函数，实现停止时候的界面切换
- (void)timerStoped
{
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(timerStoped)]) {
        
        [self.delegate timerStoped];
    }
}

- (BOOL)isTimerOver
{
    return NO;
}

+ (instancetype)countDownButtonWithTimerKey:(NSString*)timerKey
{
    if (shareCountdownButton == nil) 
    {
        shareCountdownButton = [[self alloc] init];
    }
    else if (![shareCountdownButton.timerKey isEqualToString:timerKey])
    {
        [shareCountdownButton stop];
        shareCountdownButton = nil;
        shareCountdownButton = [[self alloc] init];
    }
    
    shareCountdownButton.timerKey = timerKey;
    
    return shareCountdownButton;
}

@end
